package com.bmob.lover.ui.fragment

import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.chad.library.adapter.base.BaseQuickAdapter
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton
import com.theone.common.ext.getTimeDistance
import com.theone.common.ext.gone
import com.theone.common.ext.visible
import com.bmob.lover.R
import com.bmob.lover.data.model.bean.Menstrual
import com.bmob.lover.ui.adapter.MenstrualAdapter
import com.bmob.lover.ui.fragment.base.BasePagerFragment
import com.bmob.lover.viewmodel.MenstrualViewModel
import com.bmob.lover.viewmodel.request.MenstrualSaveViewModel
import com.theone.mvvm.core.base.fragment.BasePagerPullRefreshFragment
import com.theone.mvvm.core.databinding.BasePullFreshFragmentBinding
import com.theone.mvvm.ext.qmui.setTitleWithBackBtn
import com.theone.mvvm.ext.qmui.showFailTipsDialog

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-23 15:29
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class MenstrualFragment :
    BasePagerFragment<Menstrual, MenstrualViewModel>() {

    private val mPublishVm: MenstrualSaveViewModel by viewModels()

    private lateinit var mAddBtn: QMUIAlphaImageButton

    override fun initView(root: View) {
        super.initView(root)
        addLoadingObserve(mPublishVm)
        getTopBar()?.run {
            setTitleWithBackBtn(R.string.menstrual, this@MenstrualFragment)
            mAddBtn = addRightImageButton(R.drawable.icon_add_dark, R.id.topbar_right_button1).apply {
                gone()
                setOnClickListener {
                    mPublishVm.addMenstrual()
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mPublishVm.getObjectSuccessLiveDate().observe(this, Observer {
            onAutoRefresh()
        })
        mPublishVm.getErrorLiveData().observe(this, Observer {
            showFailTipsDialog(it)
        })
    }

    override fun onFirstLoadSuccess(data: List<Menstrual>) {
        super.onFirstLoadSuccess(data)
        updateAddStatus(data[0])
    }

    override fun onRefreshSuccess(data: List<Menstrual>) {
        super.onRefreshSuccess(data)
        updateAddStatus(data[0])
    }

    private fun updateAddStatus(data:Menstrual){
        // 距离上一次22天后才显示
        data.getStartDate()?.let {
            val diff = getTimeDistance(it)
            mAddBtn.visible(diff>22)
        }
    }

    override fun getItemSpace(): Int = 12

    override fun createAdapter(): BaseQuickAdapter<Menstrual, *> = MenstrualAdapter()

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {}

}